import React, { Component } from 'react';
import { web3, walletListContract, getWalletContract } from '../../../config';
import axios from 'axios';
import { Button, Message, Form } from '@alifd/next';
import IceContainer from '@icedesign/container';

const formItemLayout = {
  labelCol: {
    fixedSpan: 10
  },
  wrapperCol: {
    span: 10
  }
};

class Wallet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hasWallet: '',
      adminWallet: '',
      userId: '',
      walletAddress: '',
      balance: 0,
      cost: 0,
      income: 0
    };
    this.init();
  }

  // 获取localStorage的id，再访问后台获取用户数据
  // 判断用户钱包地址walletAddress是否为无
  // 无就显示“创建钱包”按钮，有就显示钱包具体内容
  init = async () => {
    const [adminWallet] = await web3.eth.getAccounts();
    const userId = localStorage.getItem("id");
    let walletAddress;
    await axios.get("http://localhost:9080/users/"+userId, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      walletAddress = res.data.walletAddress;
      console.log(walletAddress);
    }).catch(() => {
      console.log('error');
    });
    if(walletAddress) {
      this.setState({
        adminWallet: adminWallet,
        userId: userId,
        walletAddress: walletAddress,
        hasWallet: true
      });
      this.getWalletContractDetail();
    }else {
      this.setState({
        adminWallet: adminWallet,
        userId: userId,
        hasWallet: false
      });
    }
  }

  getWalletContractDetail = async () => {
    const walletContract = getWalletContract(this.state.walletAddress);
    const walletDetail = await walletContract.methods.getWalletDetail().call({
      from: this.state.adminWallet
    });
    let [_userId, _balance, _cost, _income] = Object.values(walletDetail);
    this.setState({
      balance: _balance,
      cost : _cost,
      income: _income
    });
  }

  topUp = async (e) => {
    e.preventDefault();
    const walletContract = getWalletContract(this.state.walletAddress);
    const addBalance = this.state.balance + 10;
    await walletContract.methods.setWalletDetail(addBalance, 
      this.state.cost, this.state.income).send({
        from: this.state.adminWallet
      });
    this.setState({
      balance: addBalance
    });
  }

  createWallet = async (e) => {
    e.preventDefault();
    Message.show({
      type: 'loading',
      content: '创建钱包中，请等待片刻'
    });
    await walletListContract.methods.createWallet(this.state.userId).send({
      from: this.state.adminWallet
    });
    const walletAddress = await walletListContract.methods.getLatestWalletAddress().call();
    console.log(walletAddress);
    this.setState({
      walletAddress: walletAddress,
      hasWallet: true
    });
    Message.hide();
    this.getWalletContractDetail();
    let readyWalletAddress = JSON.stringify({
      walletAddress: walletAddress
    });
    axios.put('http://localhost:9080/users/me', readyWalletAddress, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token"),
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then((res) => {
      alert('walletAddress存入数据库成功');
    }).catch(() => {
      console.log('error');
    })
  }

  render() {
    if(!this.state.hasWallet) {
      return (
        <IceContainer>
          <Button type="primary" onClick={this.createWallet} >创建钱包</Button>
        </IceContainer>
      );
    }

    return (
      <IceContainer>
        <Form style={{ width: "60%"}} {...formItemLayout}>
          <Form.Item label="用户编号">
            <p>{this.state.userId}</p>
          </Form.Item>
          <Form.Item label="钱包地址">
            <p>{this.state.walletAddress}</p>
          </Form.Item>
          <Form.Item label="余额">
            <p>{this.state.balance}</p>
          </Form.Item>
          <Form.Item label="总支出">
            <p>{this.state.cost}</p>
          </Form.Item>
          <Form.Item label="总收入">
            <p>{this.state.income}</p>
          </Form.Item>
          <Button type="primary" style={{backgroundColor: "#336666"}} onClick={this.topUp}>
            点击充值
          </Button>
        </Form>
      </IceContainer>
    );
  }
}

export default Wallet;